package com.kaluli.config;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.sitemesh.builder.SiteMeshFilterBuilder;
import org.sitemesh.config.ConfigurableSiteMeshFilter;
import org.sitemesh.content.tagrules.html.DivExtractingTagRuleBundle;
import org.springframework.core.annotation.Order;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Order(2)
public class WebAppInitializer extends
		AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { SecurityConfig.class, PersistenceConfig.class,
				ServiceConfig.class,CacheConfig.class,AppConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] { WebConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	@Override
	protected Filter[] getServletFilters() {

		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);

		return new Filter[] { characterEncodingFilter,
				new CustomSiteMeshFilter(), new OpenSessionInViewFilter() };
	}

	protected class CustomSiteMeshFilter extends ConfigurableSiteMeshFilter {

		@Override
		protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
			builder.addDecoratorPath("/*", "/decorator/default.jsp")
					// builder.addDecoratorPath("/*", "/home")
					.addExcludedPath("/res/*")
					.addExcludedPath("/login")
					.addExcludedPath("/login/*")
					.addExcludedPath("/pdf/*")
					.addExcludedPath("/project/*/devices/modify/")
					.addExcludedPath("/project/*/devicelist/modify/");;
			
			builder.addTagRuleBundles(new DivExtractingTagRuleBundle());
//			builder.addTagRuleBundles(new DivExtractingTagRuleBundle(),
//					new TagRuleBundle() {
//						@Override
//						public void install(State defaultState,
//								ContentProperty contentProperty,
//								SiteMeshContext siteMeshContext) {
//						}
//
//						@Override
//						public void cleanUp(State defaultState,
//								ContentProperty contentProperty,
//								SiteMeshContext siteMeshContext) {
//
//							defaultState.addRule("script",
//									new ExportTagToContentRule(siteMeshContext,
//											contentProperty.getChild("script"),
//											false));
//						}
//					});
		}
	}

}
